﻿using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;
using System;
using System.IO;

namespace XHD.Server
{
    public class CRM_Customer
    {
        public static BLL.CRM_Customer customer = new BLL.CRM_Customer();
        public static Model.CRM_Customer model = new Model.CRM_Customer();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public CRM_Customer()
        {
        }

        public CRM_Customer(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " CRM_Customer.create_time";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";          

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and CRM_Customer.cus_name like N'%{PageValidate.InputText(request["company"], 255)}%'";            

            if (!string.IsNullOrEmpty(request["tel"]))
                serchtxt += $" and CRM_Customer.cus_tel like N'%{PageValidate.InputText(request["tel"], 255)}%'";

            if (PageValidate.checkID(request["employee_val"]))
                serchtxt += $" and CRM_Customer.emp_id = '{PageValidate.InputText(request["employee_val"], 50)}'";
            else if (PageValidate.checkID(request["department_val"]))
                serchtxt += $" and hr_department.id  = '{PageValidate.InputText(request["department_val"], 50)}'";

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += $" and CRM_Customer.create_time >= '{PageValidate.InputText(request["startdate"], 255)}'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and CRM_Customer.create_time <= '{enddate}'";
            }
          
            
            //权限
            serchtxt += Auth();

            if (!string.IsNullOrEmpty(request["stext"]))
            {
                if (request["stext"] != "输入姓名搜索")
                    serchtxt += " and name like N'%" + PageValidate.InputText(request["stext"], 255) + "%'";
            }
            //return request.ServerVariables["http_host"];
            //return serchtxt;
            //权限
            DataSet ds = customer.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return dt;
        }

        public string save()
        {           
            model.cus_name = PageValidate.InputText(request["T_customer"], 250);           
            model.cus_tel = PageValidate.InputText(request["T_tel"], 250);            
            model.Remarks = PageValidate.InputText(request["T_remarks"], int.MaxValue);
            model.emp_id = PageValidate.InputText(request["T_employee_val"], 50);

            string id = PageValidate.InputText(request["id"], 50);
            if (PageValidate.checkID(id))
            {
                model.id = id;

                DataSet ds = customer.GetList($"id = '{id}' ");                

                if (ds.Tables[0].Rows.Count == 0)
                    return XhdResult.Error("参数不正确，更新失败！").ToString();

                DataRow dr = ds.Tables[0].Rows[0];

                bool isupdate = customer.Update(model);

                if (!isupdate) return XhdResult.Error("更新失败！").ToString();

                string logcontent = "";
                logcontent += Syslog.get_log_content(dr["cus_name"].ToString(), request["T_customer"], "客户名", dr["cus_name"].ToString(), request["T_customer"]);               
                logcontent += Syslog.get_log_content(dr["cus_tel"].ToString(), request["T_tel"], "电话", dr["cus_tel"].ToString(), request["T_tel"]);
                logcontent += Syslog.get_log_content(dr["Remarks"].ToString(), request["T_remarks"], "备注", dr["Remarks"].ToString(), request["T_remarks"]);
                logcontent += Syslog.get_log_content(dr["emp_id"].ToString(), request["T_employee_val"], "归属", dr["employee"].ToString(), request["T_employee"]);

                if (!string.IsNullOrEmpty(logcontent))
                {
                    //日志

                    string UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    string EventTitle = model.cus_name;
                    string EventType = "客户修改";
                    string EventID = model.id;

                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, logcontent );
                }

                return XhdResult.Success().ToString();
            }
            else
            {
                id = Guid.NewGuid().ToString();
                model.id = id;
                model.create_id = emp_id;
                model.create_time = DateTime.Now;

                bool isadd = customer.Add(model);

                if (!isadd) return XhdResult.Error("添加失败！").ToString();

                return XhdResult.Success().ToString();
            }
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = customer.GetList($"id = '{id}'  {Auth()} ");
            string dt = DataToJson.DataToJSON(ds);

            return dt;
        }
       
        public string del(string id)
        {
            id = PageValidate.InputText(id, 50);
            DataSet ds = customer.GetList($"id='{id}' ");
            if (ds.Tables[0].Rows.Count < 1)
                return XhdResult.Error("系统错误，找不到数据！").ToString();

            bool candel = true;
            if (uid != "admin")
            {
                //controll auth
                var getauth = new GetAuthorityByUid();
                candel = getauth.GetBtnAuthority(emp_id.ToString(), "bcdedd22-d9c5-4c74-b042-f0a75a4a35be");
                if (!candel)
                    return XhdResult.Error("无权限！").ToString();

                //dataauth
                var dataauth = new GetDataAuth();
                DataAuth auth = dataauth.GetAuth( emp_id);
                string authid = ds.Tables[0].Rows[0]["emp_id"].ToString();
                switch (auth.authtype)
                {
                    case 0: candel = false; break;
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        if (authid.IndexOf(auth.authtext) == -1) candel = false; break;
                }
                if (!candel)
                    return XhdResult.Error("权限不够！").ToString();
            }


            bool isdel = customer.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误，请检查参数！").ToString();

            //日志
            string EventType = "客户删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = ds.Tables[0].Rows[0]["cus_name"].ToString();

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();
        }       
     
        //validate website
        public string validate()
        {
            string type = PageValidate.InputText(request["type"], 50);
            string customerid = PageValidate.InputText(request["T_cid"], 50);
            string validval = "";
            string valifile = "";
            switch (type)
            {
                case "cus": validval = PageValidate.InputText(request["T_customer"], 50); valifile = "cus_name"; break;
                case "tel": validval = PageValidate.InputText(request["T_tel"], 50); valifile = "cus_tel"; break;
            }

            DataSet ds = customer.GetList($"{ valifile } = N'{validval}' and id!= '{customerid}' ");
            //context.Response.Write(" Count:" + ds.Tables[0].Rows.Count);

            if (ds.Tables[0].Rows.Count > 0)
            {
                return ("false");
            }
            return ("true");
        }
              
        private string Auth()
        {
            GetDataAuth dataauth = new GetDataAuth();
            DataAuth auth = dataauth.GetAuth(emp_id);

            switch (auth.authtype)
            {
                case 0: return $" emp_id = '{emp_id}'";
                case 1:
                case 2:
                case 3:
                case 4:
                    return $" and emp_id in ({auth.authtext}) ";
                case 5: return "";
            }

            return auth.authtype + ":" + auth.authtext;
        }
    }
}
